package com.linskating.wheat.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.linskating.wheat.common.ErrorCode;
import com.linskating.wheat.constant.UserConstant;
import com.linskating.wheat.exception.BusinessException;
import com.linskating.wheat.mapper.UserMapper;
import com.linskating.wheat.model.domain.User;
import com.linskating.wheat.model.dto.MatchUser;
import com.linskating.wheat.service.UserService;
import com.linskating.wheat.utils.AlgebraUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author LinSk
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2024-10-04 11:20:53
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService, UserConstant {

    private static final String UPLOAD_DIR = "D:\\Project\\Wheat\\backend\\wheat\\src\\main\\resources\\static\\";

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final String SALT = "LinSkating";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String wheatCode) {
        // 一次性判断多个参数是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, wheatCode)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 账户长度不小于4位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户长度不符");
        }
        // 密码长度不小于8位
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不符");
        }
        // 账户不能包含特殊字符
        String regex = "[^a-zA-Z0-9]";
        // 如果返回true说明userAccount中至少存在一个特殊字符
        boolean result = Pattern.compile(regex).matcher(userAccount).find();
        if (result) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户包含特殊字符");
        }
        //密码和校验密码是否相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码和校验密码不同");
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户重复");
        }
        // 麦穗编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wheatCode", wheatCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "麦穗编号重复, 请重试");
        }
        // 对密码进行加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes(StandardCharsets.UTF_8));
        // 向数据库中插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUsername(userAccount);
        user.setUserPassword(encryptPassword);
        user.setWheatCode(wheatCode);
        boolean saveResult = this.save(user);
        // 如果插入失败，抛异常
        if (!saveResult) {
            throw new BusinessException(ErrorCode.DATABASE_ERROR);
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 一次性判断多个参数是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 账户长度不小于4位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户长度不符");
        }
        // 密码长度不小于8位
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不符");
        }
        // 账户不能包含特殊字符
        String regex = "[^a-zA-Z0-9]";
        // 如果返回true说明userAccount中至少存在一个特殊字符
        boolean result = Pattern.compile(regex).matcher(userAccount).find();
        if (result) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户包含特殊字符");
        }
        // 将前端输送过来的密码进行加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes(StandardCharsets.UTF_8));
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        // 在数据库中根据账户和密码进行查询
        User user = userMapper.selectOne(queryWrapper);
        // 判断查询出来的用户是否为空
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.NOT_EXIT_ERROR, "账号或密码错误");
        }
        // 将查询出来的用户脱敏
        User safetyUser = getSafetyUser(user);

        request.getSession().setAttribute(USER_LOGIN_STATUS, safetyUser);
        // 返回给前端一个脱敏的对象
        return safetyUser;
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATUS);
        return 1;
    }

    @Override
    public User currentUser(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        if (request.getSession(false) == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        User attribute = (User) request.getSession().getAttribute(USER_LOGIN_STATUS);
        if (attribute == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return attribute;
    }

    @Override
    public List<User> searchUsersByAllTagsBySQL(List<String> tagsNameList, Long userId) {
        if (CollectionUtils.isEmpty(tagsNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(userQueryWrapper -> {
            for (String tagName : tagsNameList) {
                userQueryWrapper.like("tags", tagName);
            }
        });
        return userMapper.selectList(queryWrapper).stream()
                .filter(user -> !user.getId().equals(userId))
                .map(this::getSafetyUser)
                .toList();
    }

    @Override
    public List<User> searchUsersByAllTagsByMemory(List<String> tagsNameList, Long userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> usersList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        return usersList.stream().filter(user -> {
            // 该返回tags字符串是序列化之后的json字符串
            String tags = user.getTags();
            if (StringUtils.isBlank(tags)) {
                return false;
            }
            // 使用gson将序列化之后的json字符串反序列化为java对象
            Set<String> tempTagsSet = gson.fromJson(tags, new TypeToken<Set<String>>() {
            }.getType());
            tempTagsSet = Optional.ofNullable(tempTagsSet).orElse(new HashSet<>());
            // 判断这一个用户的tag列表 是否存在搜索tags列表 所有标签
            for (String tagsName : tagsNameList) {
                if (!tempTagsSet.contains(tagsName)) return false;
            }
            return true;
        }).filter(user -> !user.getId().equals(userId))
                .map(this::getSafetyUser).toList();
    }

    @Override
    public List<User> searchUsersBySomeTagsBySQL(List<String> tagsNameList, Long userId) {
        if (CollectionUtils.isEmpty(tagsNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        for (String tagsName : tagsNameList) {
            queryWrapper = queryWrapper.like("tags", tagsName).or();
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        userList = Optional.ofNullable(userList).orElse(new ArrayList<>());
        return userList.stream().filter(user -> !user.getId().equals(userId))
                .map(this::getSafetyUser)
                .toList();
    }

    @Override
    public List<User> searchUsersBySomeTagsByMemory(List<String> tagsNameList) {
        if (CollectionUtils.isEmpty(tagsNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        List<User> userList = userMapper.selectList(new QueryWrapper<>());
        Gson gson = new Gson();
        return userList.stream().filter(user -> {
            String tags = user.getTags();
            Set<String> tempTagsSet = gson.fromJson(tags, new TypeToken<Set<String>>() {
            }.getType());
            tempTagsSet = Optional.ofNullable(tempTagsSet).orElse(new HashSet<>());
            for (String tagsName : tagsNameList) {
                if (tempTagsSet.contains(tagsName)) return true;
            }
            return false;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }

    @Override
    public int updateUserInfo(User toUpdateUser) {
        if (toUpdateUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User user = userMapper.selectById(toUpdateUser.getId());
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return userMapper.updateById(toUpdateUser);
    }

    @Override
    public Page<User> recommendUsers(long thePageNum, long pageSize, long userId) {
        String redisKey = String.format("Wheat:user:recommend:%s:%d", userId, thePageNum);
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        Page<User> userPage = (Page<User>) stringObjectValueOperations.get(redisKey);
        if (userPage != null) {
            return userPage;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("id", userId);
        // 例：new Page<>(1, 10) 表示查询第 1 页，每页显示 10 条记录
        userPage = this.page(new Page<>(thePageNum, pageSize), queryWrapper);
        try {
            stringObjectValueOperations.set(redisKey, userPage, 30, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("Redis set key error", e);
        }
        return userPage;
    }

    @Override
    public List<User> matchUser(int count, User currentUser) {
        if (count <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 按需要查询的数据，查询user表中所有的符合要求的用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "tags", "userAccount", "avatarUrl").isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        // 创建一个优先队列，按照相似度降序排列
        PriorityQueue<MatchUser> userPriorityQueue = new PriorityQueue<>(count, (u1, u2) -> u2.getSimilarity() - u1.getSimilarity());
        Long currentUserId = currentUser.getId();
        // 将tags字段的数据从json转化为String字符串
        Gson gson = new Gson();
        List<String> currentUserTagsList = gson.fromJson(currentUser.getTags(), new TypeToken<List<String>>() {
        }.getType());
        // 遍历计算每个用户与该用户的相似度
        for (User user : userList) {
            // 不跟自己比
            if (Objects.equals(user.getId(), currentUserId)) continue;
            // 每个用户与该用户的相似度
            List<String> userTagsList = gson.fromJson(user.getTags(), new TypeToken<List<String>>() {
            }.getType());
            int similarityCoefficient = AlgebraUtil.SimilarityCoefficient(currentUserTagsList, userTagsList);
            // 当优先队列的实际大小比count小时，无条件添加元素
            if (userPriorityQueue.size() < count) {
                MatchUser matchUser = new MatchUser();
                matchUser.setId(user.getId());
                matchUser.setSimilarity(similarityCoefficient);
                userPriorityQueue.add(matchUser);
            } else {
                // 获取优先队列最大的相似度 peek是获取队首元素
                int minSimilarity = userPriorityQueue.peek().getSimilarity();
                // 只有相似度比队首的相似度小，就替换入队
                if (minSimilarity > similarityCoefficient) {
                    userPriorityQueue.poll();
                    MatchUser matchUser = new MatchUser();
                    matchUser.setId(user.getId());
                    matchUser.setSimilarity(similarityCoefficient);
                    userPriorityQueue.add(matchUser);
                }
            }
        }
        // 直接在内存查，此方法我只查询了一次数据库
        List<Long> matchUserIdlist = userPriorityQueue.stream().map(MatchUser::getId).toList();
        userList = userList.stream().filter(user -> matchUserIdlist.contains(user.getId())).toList();
        return userList;
    }

    @Override
    public String updateAvatarUrl(MultipartFile file, Long id) {
        String fileUrl;
        try{
            if (file.isEmpty()) {
                throw new BusinessException(ErrorCode.NULL_ERROR);
            }
            String filename = file.getOriginalFilename();
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                // 如果目录不存在，则创建
                if (!uploadDir.mkdirs()) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR);
                }
            }
            file.transferTo(new File(UPLOAD_DIR + filename));
            fileUrl = "http://localhost:8080/api/" + filename;
            UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
            userUpdateWrapper.eq("id", id)
                    .set("avatarUrl", fileUrl);
            this.update(userUpdateWrapper);
        } catch (BusinessException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return fileUrl;
    }

    @Override
    public boolean isNotAdmit(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATUS);
        return user == null || user.getUserRole() != ADMIN_ROLE;
    }

    @Override
    public boolean isNotAdmit(User currentUser) {
        return currentUser == null || currentUser.getUserRole() != ADMIN_ROLE;
    }

    @Override
    public User getSafetyUser(User orginalUser) {
        if (orginalUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "脱敏对象为空");
        }
        User safetyUser = new User();
        safetyUser.setId(orginalUser.getId());
        safetyUser.setUsername(orginalUser.getUsername());
        safetyUser.setUserAccount(orginalUser.getUserAccount());
        safetyUser.setGender(orginalUser.getGender());
        safetyUser.setAvatarUrl(orginalUser.getAvatarUrl());
        safetyUser.setUserRole(orginalUser.getUserRole());
        safetyUser.setWheatCode(orginalUser.getWheatCode());
        safetyUser.setPhone(orginalUser.getPhone());
        safetyUser.setEmail(orginalUser.getEmail());
        safetyUser.setTags(orginalUser.getTags());
        safetyUser.setUserStatus(orginalUser.getUserStatus());
        safetyUser.setCreateTime(orginalUser.getCreateTime());
        return safetyUser;
    }

    @Override
    public String getUniqueUID() {
        // 获取当前时间戳（毫秒级）
        long timestamp = Instant.now().toEpochMilli();
        // 生成随机UUID
        String uuid = IdUtil.fastUUID();
        return timestamp + uuid;
    }
}
